package hashtable;

import java.util.HashMap;


/**
 * 两数之和
 * @author shkstart
 * @create 2021-04-26 12:08
 */
public class TwoSumDemo {

    public static void main(String[] ages){

      int []  nums = new int[]{2,7,1,3,5};

      int target = 9;

      int [] myIndex = twosum2 (nums,target);

        for ( int i :myIndex) {
            System.out.println(i);
        }
    }
//      用哈希map
     public static int[] twosum(int[] nums, int target) {
        HashMap<Integer,Integer> hashMap = new HashMap();

        for (int i = 0; i <nums.length ; i++) {
           int item  = target-nums[i];
            if (hashMap.containsKey(item)) {
                return  new int []{hashMap.get(item),i};
            }
            hashMap.put(nums[i],i);
        }
        return null;
    }
//    暴力解题
      public static int[] twosum2(int[] nums, int target){
          for (int i = 0; i <nums.length ; i++) {
              for (int j = i+1; j <nums.length ; j++) {
                  if (target == nums[i] +nums[j]){
                   return new int[]{i,j};
                  }
              }
          }
          return null;
      }
}
